import json
import os
from cfg import Config
from flask import redirect, url_for, Blueprint, render_template, request, jsonify
from cfg import Development
from ..blog.models import Article, Category, db, Tag, Attachment

admin_bp = Blueprint('admin', __name__, url_prefix='/bg')


@admin_bp.route('/')
def index():
    return render_template('admin/index.html')


@admin_bp.route('/article')
def mng_article():
    return render_template('admin/module/article.html')


@admin_bp.route('/query_art')
def get_article():
    page = request.args.get('page', type=int, default=1)  # 当前页
    limit = request.args.get('limit', type=int, default=10)  # 一页条数
    article_pg = Article.query.paginate(page=page, per_page=limit)
    article_list = []
    for item in article_pg.items:
        print(item)
        row = {
            'id': item.id,
            'title': item.title,
            'read_count': item.read_count,
            'category': item.category.name,
            'add_time': item.add_time.strftime("%Y-%m-%d"),
            'upd_time': item.upd_time.strftime("%Y-%m-%d")
        }
        print('>>', row)
        article_list.append(row)
    data = {
        "code": 0,
        "msg": "",
        "count": article_pg.total,
        "data": article_list
    }
    print(data)
    return jsonify(data)


@admin_bp.route('/upload', methods=['POST'])
def file_upload():
    """
    文章管理-资源上传API
    :return:
    """
    file = request.files.get('file')
    name = request.form['name']
    size = request.form['size']
    file_path = f'static/uploads/files/{name}'
    print(file_path)
    file.save(Config.BASE_DIR / file_path)
    attachment = Attachment(file_name=name, file_size=size, file_path=file_path)
    db.session.add(attachment)
    db.session.commit()
    return {'id': attachment.id, 'url': url_for('static', filename=f'uploads/files/{name}')}


@admin_bp.route('/add_article', methods=['POST'])
def add_art():
    """
    文章管理-新增文章API
    :return:
    """
    form_data = request.form
    tags = json.loads(form_data['tags'])
    tags_obj = [Tag.query.get(tag_id) for tag_id in tags.keys()]

    article_obj = Article(
        title=form_data['title'],
        content_md=form_data['markdown'],
        content_html=form_data['html'],
        category_id=form_data['category'],
        tags=tags_obj
    )

    img_list = json.loads(form_data['img_list'])
    ids = [i['id'] for i in img_list]
    atchmts = Attachment.query.filter(Attachment.id.in_(ids)).all()
    article_obj.attachments.extend(atchmts)

    db.session.add(article_obj)
    db.session.commit()

    return 'success'


@admin_bp.route('/edit_art')
def edit_article():
    category_list = Category.query.all()
    tag_list = Tag.query.all()
    return render_template('admin/module/edit_art.html', **locals())


@admin_bp.route('/category')
def mng_category():
    return render_template('admin/module/category.html')


@admin_bp.route('/query_category')
def get_category():
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=1)
    category_pg = Category.query.paginate(page=page, per_page=limit)
    category_list = []
    for item in category_pg.items:
        row = {
            'id': item.id,
            'name': item.name,
            'add_time': item.add_time.strftime("%Y-%m-%d"),
            'upd_time': item.upd_time.strftime("%Y-%m-%d")
        }
        category_list.append(row)
    data = {
        'code': 0,
        'msg': '',
        'count': category_pg.total,
        'data': category_list
    }
    return jsonify(data)


@admin_bp.route('/add_category', methods=['POST'])
def add_category():
    category_name = request.form.get('value')
    catg = Category.query.filter_by(name=category_name).first()
    if not catg:
        category = Category(name=category_name)
        db.session.add(category)
        db.session.commit()
        return 'success'
    return 'existed'


@admin_bp.route('/tag')
def mng_tag():
    return render_template('admin/module/tag.html')


@admin_bp.route('/add_tag', methods=['POST'])
def add_tag():
    """
    标签管理-新增标签API
    :return:
    """
    tag_name = request.form['tag_name']
    tag_color = request.form['tag_color']
    tag_ = Tag.query.filter_by(name=tag_name).first()
    if not tag_:
        tag_obj = Tag(name=tag_name, color=tag_color)
        db.session.add(tag_obj)
        db.session.commit()
        return 'success'
    return 'existed'


@admin_bp.route('/query_tag')
def get_tag():
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=5)
    tag_pg = Tag.query.paginate(page=page, per_page=limit)
    tag_list = []
    for item in tag_pg.items:
        row = {
            'id': item.id,
            'name': item.name,
            'color': item.color,
            'add_time': item.add_time.strftime("%Y-%m-%d"),
            'upd_time': item.upd_time.strftime("%Y-%m-%d")
        }
        tag_list.append(row)
    data = {
        'code': 0,
        'data': tag_list,
        'count': tag_pg.total,
        'msg': ''
    }
    return jsonify(data)
